#!/home/cs1010/anaconda3/envs/mqtt_admin/bin/python
import time
import ssl
import paho.mqtt.client as mqtt

# MQTT 服务器信息
MQTT_BROKER = "x7911085.ala.cn-hangzhou.emqxsl.cn"
MQTT_PORT = 8883

# MQTT 客户端 ID
CLIENT_ID = "python_publisher"

# 话题和消息
TOPIC = "test/topic"
MESSAGE = "Hello, MQTT!"

username = 'admin'
password = '!((@0927Cc!ESP32S3'


# MQTT 客户端 ID
CLIENT_ID = "python_publisher"

# 话题和消息
TOPIC = "test/topic"
MESSAGE = "Hello, MQTT!"

# 当连接成功时的回调函数
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
    else:
        print(f"Failed to connect, return code {rc}")

# 创建 MQTT 客户端实例
client = mqtt.Client(client_id=CLIENT_ID)

# 设置连接成功时的回调函数
client.on_connect = on_connect

# 设置 TLS/SSL 配置
client.tls_set(cert_reqs=ssl.CERT_NONE)
client.tls_insecure_set(True)

client.username_pw_set(username, password)

# 连接到 MQTT 服务器
client.connect(MQTT_BROKER, MQTT_PORT)

# 启动循环处理网络流量
client.loop_start()

# 发布消息
msg_count = 0
while True:
    time.sleep(1)
    msg = f"messages: {msg_count}"
    result = client.publish(TOPIC, msg)
    # result: [0, 1]
    status = result[0]
    if status == 0:
        print(f"Send `{msg}` to topic `{TOPIC}`")
    else:
        print(f"Failed to send message to topic {TOPIC}")
    msg_count += 1


# 停止循环
client.loop_stop()

# 断开连接
client.disconnect()    
